import Vue from 'vue'
import Router from 'vue-router'
import { routes } from './router'
import { setTitle, hasToken } from '@/lib/util'
import Store from '@/store'

Vue.use(Router)

const router = new Router({
  routes
})

const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
  // loading begin
  to.meta && setTitle(to.meta.title)
  const token = hasToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      path: '/home' // 跳转到home页
    })
  } else {
    // next()
    // 判断菜单/路由权限
    if (!Store.state.router.hasGetRole) {
      Store.dispatch('userInfo').then(menuList => {
        Store.dispatch('concatRoutes', menuList).then(routers => {
          router.addRoutes(routers)
          next({ ...to, replace: true })
        }).catch(() => {
          next({ name: LOGIN_PAGE_NAME })
        })
      })
    } else {
      next()
    }
  }
})

// router.beforResolve() 方法同router.beforeEach()

router.afterEach((to, from) => {
  // loading close
})

export default router
